package dwz.web;

//import javax.inject.Inject;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.patchca.color.*;
import org.patchca.filter.predefined.WobbleRippleFilterFactory;
import org.patchca.font.RandomFontFactory;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.text.renderer.BestFitTextRenderer;
import org.patchca.text.renderer.TextRenderer;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;

import dwz.business.book.Book;
import dwz.business.book.BookServiceMgr;
import dwz.business.book.Chapter;
import dwz.business.book.ChapterConditionVO;

@Controller
public class IndexController extends BaseController{
	private Logger logger = Logger.getLogger(IndexController.class);
	private static ConfigurableCaptchaService ccs = new ConfigurableCaptchaService();  
    private static ColorFactory cf = new SingleColorFactory(new Color(25, 60, 170));  
    private static TextRenderer tr = new BestFitTextRenderer();  
    private static RandomFontFactory ff = new RandomFontFactory();  
    private static RandomWordFactory rwf = new RandomWordFactory();  
    private static WobbleRippleFilterFactory wrff = new WobbleRippleFilterFactory();   //摆波纹  
	// @Inject
	// private User user;

	@Autowired
	private BookServiceMgr bookMgr;
	
	@Autowired
	private DefaultKaptcha captchaProducer;
	
	@RequestMapping("")
	public String index() {
		return "/login";
	}

	@RequestMapping("/captcha-image")
	public ModelAndView getPatchcaImage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		rwf.setCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyz");  
        ff.setRandomStyle(false);  
        ff.setMaxSize(25);  
        ff.setMinSize(20);  
        ccs.setTextRenderer(tr);
        ccs.setFontFactory(ff);  
        ccs.setWordFactory(rwf);  
        ccs.setColorFactory(cf);  
        ccs.setWidth(50);  
        ccs.setHeight(30);
        response.setContentType("image/png");  
        response.setHeader("cache", "no-cache");  
        rwf.setMaxLength(4);  
        rwf.setMinLength(4);  
        HttpSession session = request.getSession(true);  
        OutputStream os = response.getOutputStream();  
        ccs.setFilterFactory(wrff);
        String captcha = EncoderHelper.getChallangeAndWriteImage(ccs, "png", os);  
        logger.info("captcha is "+captcha);
        session.setAttribute("captcha", captcha);  
        os.flush();
        os.close(); 
		return null;
	}
	
	@RequestMapping("/captcha")
	public void genCaptchaImage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setDateHeader("Expires", 0);   
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		String capText = captchaProducer.createText();
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,
				capText);
		BufferedImage bi = captchaProducer.createImage(capText);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);

		try {
			out.flush();
		} finally {
			out.close();
		} 

	}
	
	@RequestMapping("/books")
	public String books(Model model) {System.out.println(getMessage("ui.title"));
		List<Book> bookList = bookMgr.searchBook(null, null, 0, 100);
		model.addAttribute(bookList);
		return "/books";
	}
	
	@RequestMapping("/chapters")
	public String chapters(ChapterConditionVO vo, Model model) {
		List<Chapter> chapters = bookMgr.searchChapters(vo);
	
		model.addAttribute("chapters", chapters);
		
		return "/chapters";
	}
	
	@RequestMapping("/chapter/{chapterId}")
	public String chapter(@PathVariable("chapterId") int chapterId, Model model) {

		Chapter chapter = bookMgr.getChapter(chapterId);
		Book book = bookMgr.getBook(chapter.getBookId());
		model.addAttribute(chapter);
		model.addAttribute(book);

		return "/chapter";
	}
}